package com.beerandjesus.sportofkings.handicapper.app;

import com.beerandjesus.sportofkings.handicapper.model.*;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.HorseRace;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.dao.Database;
import com.beerandjesus.sportofkings.handicapper.dao.aspect.TransactionBoundary;
import com.beerandjesus.sportofkings.handicapper.strategy.CramerJockeyRatingResolver;

import java.util.List;
import java.util.ArrayList;

/**
 * Date: Jul 8, 2012
 * Time: 5:14:28 PM
 */
public class JockeyRatingDatabaseBuilderImpl implements JockeyRatingDatabaseBuilder {
    private CardAnalyzer cardAnalyzer;
    private Database database;
    private CramerJockeyRatingResolver cramerJockeyRatingResolver;

    @TransactionBoundary(datasources = Database.Datasource.JOCKEY)
    public void addAllJockeys(CardVO card) throws CardAnalyzerException {
        List<HorseRace> list = getCardAnalyzer().parseCard(card);
        List<JockeyRating> jockeyRatings = new ArrayList<JockeyRating>();
        for (HorseRace hr : list) {
            for (Horse h : hr.getHorses()) {
                TrainerJockeyOwner tjo = h.getTrainerJockeyOwner();
                JockeyAtDistanceOrOnTurf jock = null;
                if (tjo != null) {
                    jock = tjo.getJockeyAtDistanceOrOnTurf();
                }
                CramerJockeyRating r = getCramerJockeyRatingResolver().getRating(tjo, jock);
                if (r != null && tjo != null && tjo.getJockeyName() != null) {
                    JockeyRatingImpl rating = new JockeyRatingImpl();
                    rating.setJockeyName(tjo.getJockeyName());
                    rating.setRating(r);
                    jockeyRatings.add(rating);
                }
            }

        }
        getDatabase().save(jockeyRatings);
    }

    public CardAnalyzer getCardAnalyzer() {
        return cardAnalyzer;
    }

    public void setCardAnalyzer(CardAnalyzer cardAnalyzer) {
        this.cardAnalyzer = cardAnalyzer;
    }

    public Database getDatabase() {
        return database;
    }

    public void setDatabase(Database database) {
        this.database = database;
    }

    public CramerJockeyRatingResolver getCramerJockeyRatingResolver() {
        return cramerJockeyRatingResolver;
    }

    public void setCramerJockeyRatingResolver(CramerJockeyRatingResolver cramerJockeyRatingResolver) {
        this.cramerJockeyRatingResolver = cramerJockeyRatingResolver;
    }
}
